<template>
  <base-breadcrumb
    class="UpdateSafetyStarHonour-container fixed-container"
    :title="breadcrumbTitle"
    v-loading="loadingState.isDetail"
  >
    <a-card>
      <title-name title="基本信息" />
      <custom-form
        ref="ruleForm"
        :rules="rules"
        :isValidate="true"
        :form-list="formItemList"
        :form="formInfo"
        :edit-model="pageType === 'look' ? 'V' : ''"
        :is-emit="false"
        @selectOrg="selectOrg"
      >
        <template v-slot:starTable>
          <title-name title="安全之星"></title-name>
          <div class="table-operator" v-if="!isDisabled">
            <a-button type="primary" icon="plus" @click="updatePersonList('add')">添加行</a-button>
          </div>
          <a-table
            :pagination="false"
            :rowKey="(record) => record.id || record.fakeId"
            :columns="columns"
            :data-source="dataList"
            bordered
          >
            <template v-for="col in ['starName', 'num']" :slot="col" slot-scope="text, record, index">
              <div style="width: 200px" :key="col" class="requiredFormItem" v-if="!isDisabled">
                <a-select
                  :showSearch="true"
                  v-if="col === 'starName'"
                  v-model="record.starName"
                  @change="handleStarChanged($event, record)"
                  @search="handlePersonSearch"
                >
                  <a-spin v-if="loadingState.personList" slot="notFoundContent" size="small" />
                  <a-select-option v-for="item in personList" :key="item.value" :value="item.value">
                    <span :title="`${item.subContractorName}-${item.subTeam}`">{{ item.label }}</span>
                  </a-select-option>
                </a-select>
                <BaseInputNumber :min="0" v-if="col === 'num'" v-model="record.num" />
              </div>
              <span v-else>{{ text }}</span>
            </template>
            <div v-if="!isDisabled" class="pub-table-list-action" slot="action" slot-scope="text, record, index">
              <span @click="updatePersonList('delete', index)">删除</span>
            </div>
          </a-table>
        </template>
        <template v-slot:team>
          <title-name title="平安班组" />
          <a-row v-for="(item, index) in safetyStarCiteTeamDTOS" :key="index">
            <a-col :span="8">
              <a-form-model-item prop="teamName" label="平安班组" class="requiredFormItem">
                <a-select :showSearch="true" :disabled="isDisabled" :options="teamList" v-model="item.teamName">
                  <a-spin v-if="loadingState.teamList" slot="notFoundContent" size="small" />
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item prop="reward" label="奖励金额（元）" class="requiredFormItem">
                <BaseInputNumber :disabled="isDisabled" :min="0" v-model="item.reward" />
              </a-form-model-item>
            </a-col>
            <a-col :span="8" v-if="!isDisabled">
              <a-button
                style="margin-top: 3px"
                v-show="index === safetyStarCiteTeamDTOS.length - 1"
                class="ml12"
                type="default"
                icon="plus"
                @click="updateTeam('add')"
              ></a-button>
              <a-button
                style="margin-top: 3px"
                v-show="index < safetyStarCiteTeamDTOS.length - 1"
                class="ml12"
                type="default"
                icon="minus"
                @click="updateTeam('delete', index)"
              ></a-button>
            </a-col>
          </a-row>
        </template>
        <template v-slot:total>
          <title-name title="奖励总金额" />
        </template>
        <template v-slot:totalNum>
          <BaseInputNumber :min="0" :disabled="true" :value="totalNum" />
        </template>
        <template #fileInfoVOS>
          <template v-if="!isDisabled">
            <upload-list
              :businessCode="'SHE11'"
              :editModel="2"
              :uploadArrys.sync="formInfo.fileInfoVOS"
              uploadType="image"
              multiple
            ></upload-list>
          </template>
          <file-link v-else :fileList="formInfo.fileInfoVOS" style="margin-top: -3px"></file-link>
        </template>
      </custom-form>
    </a-card>
    <div class="tool-btns tool-btns--fixed page-btn-right-top">
      <a-button
        v-if="!isDisabled"
        class="ml12"
        type="primary"
        :loading="loadingState.SUBMITTED"
        :disabled="loadingState.isDetail"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button class="ml12" type="default" @click="handleClose"> 关闭 </a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
import UploadList from '@/components/UploadList'
import Vue from 'vue'
import Moment from 'moment'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import {
  addData,
  updateData,
  getDetail,
  getSubpersonByProject,
  getTeamnByProject
} from '@/api/safetySupervision/safetyStar/safetyStarHonour.js'

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    customRender() {
      return Number(arguments[2]) + 1
    }
  },
  {
    title: '安全之星',
    dataIndex: 'starName',
    scopedSlots: { customRender: 'starName' }
  },
  {
    title: '奖励金额（元）',
    dataIndex: 'num',
    scopedSlots: { customRender: 'num' }
  },
  {
    title: '分包单位',
    dataIndex: 'subContractorName',
    scopedSlots: { customRender: 'subContractorName' }
  },
  {
    title: '班组',
    dataIndex: 'subTeam',
    scopedSlots: { customRender: 'subTeam' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'UpdateSafetyStarHonour',
  components: {
    UploadList
  },
  data() {
    return {
      formInfo: {
        month: Moment(new Date()).format('YYYY-MM'),
        fileInfoVOS: [],
        projectId:null,
      },
      loadingState: {
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false,
        personList: false,
        teamList: false
      },
      columns, // 安全之星的列配置
      dataList: [], // 安全之星列表
      listDefaultLen: 200, // 列表默认长度
      personList: [], // 安全之星的人员列表，只显示默认列表长度的数据
      originPersonList: [], // 记录真正的人员列表
      teamList: [], // 班组列表
      safetyStarCiteTeamDTOS: [
        // 平安班组列表
        {
          id: 'fakeId-1',
          teamName: '',
          reward: 0
        }
      ]
    }
  },
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '新增行为安全之星集中表彰',
        edit: '编辑行为安全之星集中表彰',
        look: '查看行为安全之星集中表彰'
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: false
        },
        // {
        //   label: '分公司',
        //   keyName: 'branchComId',
        //   viewName: 'branchComName',
        //   type: SelectSubCompany,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: this.pageType === 'add'
        //   },
        //   selectChange: (e) => {
        //     this.formInfo.branchComName = e.orgName || ''
        //   },
        //   disabled: true
        // },
        // {
        //   label: '项目名称',
        //   keyName: 'projectId',
        //   viewName: 'projectName',
        //   type: SelectProject,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: this.pageType === 'add',
        //     keyValue: 'branchComId',
        //     isEdit: true,
        //     form: this.formInfo
        //   },
        //   selectChange: (e) => {
        //     this.formInfo.projectName = e.name || ''
        //     this.getExtraListByProject(e.code, {
        //       fn: getSubpersonByProject,
        //       keyName: 'personList',
        //       filterFn: this.filterPersonList,
        //       resolveResultFn: (list) => {
        //         this.originPersonList = list
        //         this.personList = list.slice(0, this.listDefaultLen)
        //       }
        //     })
        //     this.getExtraListByProject(e.code, {
        //       fn: getTeamnByProject,
        //       keyName: 'teamList',
        //       filterFn: this.filterTeam
        //     })
        //   },
        //   disabled: true
        // },
        {
          label: '月份',
          keyName: 'month',
          type: 'a-month-picker',
          attrs: {
            valueFormat: 'YYYY-MM'
          },
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          slot: true,
          keyName: 'starTable',
          span: 24
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'team',
          span: 24
        },
        {
          slot: true,
          keyName: 'total',
          span: 24
        },
        {
          label: '总金额',
          keyName: 'totalNum',
          slot: true
        },
        {
          slot: true,
          keyName: 'placeholder',
          span: 16
        },
        {
          slot: true,
          label: '照片上传',
          keyName: 'fileInfoVOS'
        }
      ]
    },
    rules() {
      const map = {}
      this.formItemList.map((item) => {
        if (item.rules) {
          map[item.keyName] = item.rules
        }
      })
      return map
    },
    // 奖励总金额，计算安全之星列表和平安班组列表里的金额综合
    totalNum() {
      return this.calcTotal(this.dataList, 'num') + this.calcTotal(this.safetyStarCiteTeamDTOS, 'reward')
    }
  },
  created() {
    this.initPage()
    this.getDetailReq()
  },
  methods: {
    selectOrg(val) {
      if(val.length > 1) {
        this.formInfo.branchComName = val[val.length - 2].orgName
        this.formInfo.branchComId = val[val.length - 2].orgId
            this.formInfo.projectName =val[val.length - 1].projectName
            this.getExtraListByProject(this.formInfo.projectId, {
              fn: getSubpersonByProject,
              keyName: 'personList',
              filterFn: this.filterPersonList,
              resolveResultFn: (list) => {
                this.originPersonList = list
                this.personList = list.slice(0, this.listDefaultLen)
              }
            })
            this.getExtraListByProject(this.formInfo.projectId, {
              fn: getTeamnByProject,
              keyName: 'teamList',
              filterFn: this.filterTeam
            })
      }
    },
    filterTeam(item) {
      return {
        value: item,
        label: item
      }
    },
    filterPersonList(item) {
      return {
        value: `${item.starName}-${item.subContractorName}-${item.subTeam}`,
        label: item.starName,
        subContractorName: item.subContractorName,
        subTeam: item.subTeam
      }
    },
    handlePersonSearch(val) {
      if (!val) {
        this.personList = this.originPersonList.slice(0, this.listDefaultLen) // 需要对数据进行截取，避免页面卡顿，同时考虑到用户不会一一浏览上千条数据，因此不做滚动懒加载
        return
      }
      this.personList = this.originPersonList
        .filter((item) => item.label && item.label.indexOf(val) > -1)
        .slice(0, this.listDefaultLen)
    },
    /**
     * 计算数组内的某个字段总和
     * @param {Array<object>} arr - 计算数组
     * @param {String} keyName - 字段名
     * @returns 计算出的总和
     */
    calcTotal(arr, keyName) {
      if (!arr || !arr.length) return 0
      return arr.reduce((pre, cur) => {
        const target = Number(cur[keyName])
        return Number.isFinite(target) ? pre + target : pre
      }, 0)
    },
    /**
     * 更新平安班组列表
     * @param {String} actionType - 操作类别 'add' | 'delete'
     * @param {Number} index - 操作序号
     */
    updateTeam(actionType, index) {
      const map = {
        add: () => {
          this.safetyStarCiteTeamDTOS.push({
            teamName: '',
            reward: '',
            id: `fakeId-${this.safetyStarCiteTeamDTOS.length + 1}`
          })
        },
        delete: () => {
          this.safetyStarCiteTeamDTOS.splice(index, 1)
        }
      }
      map[actionType] && map[actionType]()
    },
    handleStarChanged(newVal, record) {
      const targeData = this.personList.find((item) => item.value === newVal)
      record.subContractorName = targeData.subContractorName
      record.subTeam = targeData.subTeam
      this.handlePersonSearch()
    },
    /**
     * 更新安全之星列表
     * @param {String} actionType - 操作类别 'add' | 'delete'
     * @param {Number} index - 操作序号
     */
    updatePersonList(actionType, index) {
      const actionMap = {
        add: () => {
          this.dataList.push({
            starName: '',
            num: '',
            subContractorName: '',
            subTeam: '',
            id: `fakeId-${this.dataList.length + 1}`
          })
        },
        delete: () => {
          this.dataList.splice(index, 1)
        }
      }
      actionMap[actionType] && actionMap[actionType]()
    },

    /**
     * 获取项目下的分包人员列表和班组列表
     * @param {String} projectId - 项目ID
     * @param {Object} options - 请求配置
     * @param {Function} options.fn - 请求接口
     * @param {String} keyName - 需要操作的数组名
     * @param {Function} filterFn - 过滤函数，可以使用该参数对返回结果进行处理。入参为每一个数据项，需要返回一个过滤后的对象
     * @param {Function} resolveResultFn - 结果处理函数，该函数入参为最后得到的列表数组，可以根据需要对该列表进行取值、赋值
     */
    async getExtraListByProject(projectId, { fn, keyName, filterFn, resolveResultFn } = {}) {
      try {
        this.loadingState[keyName] = true
        const params = {
          projectId: projectId
        }
        const res = await fn(params)
        this[keyName] = res.data.map((item) => {
          if (filterFn) {
            return filterFn(item)
          }
          return item
        })
        resolveResultFn && resolveResultFn(this[keyName])
      } catch (e) {
        console.error(e)
      }
      this.loadingState[keyName] = false
    },
    /**
     * 获取详情
     */
    async getDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id
        }
        this.loadingState.isDetail = true
        const res = await getDetail(params)
        this.formInfo = {
          ...this.formInfo,
          ...res.data
        }
        this.safetyStarCiteTeamDTOS = res.data.safetyStarCiteTeamDTOS || []
        this.dataList = res.data.safetyStarCitePeopleDTOS || []
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    handleClose() {
      this.$close()
    },
    /**
     * 初始化页面数据
     */
    initPage() {
      // 新增时，生成创建人和创建时间
      if (this.pageType === 'add') {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        this.formInfo = {
          ...this.formInfo,
          creatorName: userInfo.name,
          createTime: curDate
        }
        this.formInfo.projectId = this.$userInfo().currentPost.projectId;
        console.log(this.formInfo.projectId,11111111111)
      }
    },
    /**
     * 验证必填额外的信息（安全之星和平安班组）
     */
    validateExtra() {
      try {
        this.dataList.forEach((item, index) => {
          if (!item.starName || (!item.num && item.num !== 0)) {
            this.$message.warning(`请完善安全之星第${index + 1}行的数据`)
            throw new Error('Extra valid error')
          }
        })
        this.safetyStarCiteTeamDTOS.forEach((item, index) => {
          if (!item.teamName || (!item.reward && item.reward !== 0)) {
            this.$message.warning(`请完善平安班组第${index + 1}行的数据`)
            throw new Error('Extra valid error')
          }
        })
      } catch {
        return false
      }
      return true
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          if (!this.validateExtra()) return
          this.invokeSave(actionName)
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 如果keyName字段的值包含 'fakeId'，那么就删除该字段(避免报错)
     */
    deleteFakeId(arr, keyName = 'id') {
      return (
        (arr &&
          arr.map((item) => {
            const target = { ...item }
            if (target[keyName] && target[keyName].indexOf('fakeId') > -1) {
              delete target[keyName]
            }
            return target
          })) ||
        []
      )
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const params = {
          ...this.formInfo,
          safetyStarCiteTeamDTOS: this.deleteFakeId(this.safetyStarCiteTeamDTOS),
          safetyStarCitePeopleDTOS: this.deleteFakeId(this.dataList).map((item) => {
            return {
              ...item,
              starName: item.starName.split('-')[0]
            }
          }),
          totalNum: this.totalNum
        }
        const fn = this.pageType === 'add' ? addData : updateData
        await fn(params)
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '提交成功')
        this.handleClose()
        this.loadingState[actionName] = false
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.upload-wrapper {
  padding-bottom: 40px;
}
</style>
